package middleware

import (
	"fmt"
	"net/http"
	"strings"

	userScopeClient "go-zero-admin/apps/system/cmd/rpc/client/userscope"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/pkg/ctxdata"
	"go-zero-admin/pkg/result"
	"go-zero-admin/pkg/xerr"

	"github.com/duke-git/lancet/v2/strutil"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type CheckUrlAuthMiddleware struct {
	UserScopeRpc userScopeClient.UserScope
}

func NewCheckUrlAuthMiddleware(userScopeRpc userScopeClient.UserScope) *CheckUrlAuthMiddleware {
	return &CheckUrlAuthMiddleware{
		UserScopeRpc: userScopeRpc,
	}
}

func (m *CheckUrlAuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		uid := ctxdata.GetUidFromCtx(ctx)
		url := r.RequestURI
		if strings.Index(url, "/") != -1 {
			url = strutil.After(url, "/")
		}
		if strings.Index(url, "?") != -1 {
			url = strutil.Before(url, "?")
		}

		// 检查权限
		hasAuthResp, err := m.UserScopeRpc.CheckUserRuleAuth(ctx, &syspb.CheckUserRuleAuthReq{
			UserId: uid,
			Url:    url,
		})
		if err != nil || !hasAuthResp.GetIsHasAuth() {
			errMsg := fmt.Sprintf("用户ID：%d，没有访问：%s，路径的的权限，请联系管理员", uid, url)
			logx.WithContext(r.Context()).Errorf("【SYSTEM-API-AUTH-ERR】: %+v;", xerr.NewErrCodeMsg(http.StatusUnauthorized, errMsg))
			httpx.WriteJson(w, http.StatusUnauthorized, result.Error(http.StatusUnauthorized, errMsg))
			return
		}

		next(w, r)
	}
}
